package com.qin.controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qin.entity.Book;
import com.qin.entity.Order;
import com.qin.entity.OrderBook;
import com.qin.entity.User;
import com.qin.service.BookService;
import com.qin.service.OrderBookService;
import com.qin.service.OrderService;
import com.qin.service.impl.BookServiceImpl;
import com.qin.service.impl.OrderBookServiceImpl;
import com.qin.service.impl.OrderServiceImpl;
import com.qin.vo.BookVo;
import com.qin.vo.OrderVo;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;

/**
 * 处理order请求，来到order页面，或者是删除订单记录
 */
@WebServlet("/orders")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private OrderService orderService = new OrderServiceImpl();
	private OrderBookService orderBookService = new OrderBookServiceImpl();
	private BookService bookService = new BookServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		// 查询这个user 下的所有订单
		List<Order> querryOrdersByUserId = orderService.querryOrdersByUserId(user.getId());
		
		// 把这些订单转换成订单VO，并排序（按照时间，从大到小）
		List<OrderVo> orderVos = ordersParseOrderVos(querryOrdersByUserId).stream().sorted(Comparator.comparing(OrderVo::getCreateTime).reversed()).collect(Collectors.toList());
		
		// 这转换好的订单VO放到请求域中
		request.setAttribute("orders",orderVos);
		
		request.getRequestDispatcher("/WEB-INF/user/order.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 处理需要筛选的订单请求,拿到需要筛选的订单状态
		String status = request.getParameter("status");
		String payTime = request.getParameter("payTime");
		
		// 先拿到订单
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		List<Order> querryOrdersByUserId = orderService.querryOrdersByUserId(user.getId());
		
		// 对订单进行过滤
		List<Order> screenByStatusAndPayTime = screenByStatusAndPayTime(querryOrdersByUserId,status,payTime);
		
		// 把订单转换成订单VO
		List<OrderVo> ordersParseOrderVos = ordersParseOrderVos(screenByStatusAndPayTime);
		
		// 最后把订单转成JSON返回
		response.getWriter().write(JSONUtil.toJsonStr(ordersParseOrderVos));
	}

	/**
	 * 传入要求的订单状态和订单支付时间，对用户的订单进行过滤
	 * @param orders 要过滤的原用户订单
	 * @param status 订单状态
	 * @param payTime 订单支付时间
	 * @return 过滤后的订单
	 */
	public List<Order> screenByStatusAndPayTime(List<Order> orders,String status,String payTime){
		// 对订单进行筛选
		return orders.stream().filter(order1->{
			// 先对状态进行筛选
			if(StrUtil.equals(status, "1")) {
				// 代表全部订单
				return true;
			}else if(StrUtil.equals(status, "2")) {
				// 代表为未提交订单
				return !order1.getPaymentStatus();
			}else if(StrUtil.equals(status, "3")){
				// 代表未评论
				return !order1.getCommentStatus();
			}else {
				StaticLog.error(new RuntimeException("查询订单时，携带的状态异常！"));
				return false;
			}
		}).filter(order2->{
			// 再对支付订单的时间进行筛选
			if(StrUtil.equals(payTime, "1")) {
				// 代表30天以内
				// 先获取订单的时间
				LocalDateTime orderTime = LocalDateTimeUtil.of(order2.getCreateTime());
				
				return LocalDateTimeUtil.between(orderTime, LocalDateTimeUtil.now()).toDays() < 31;
			}else if(StrUtil.equals(payTime, "2")) {
				// 代表为九十天以内
				// 先获取订单的时间
				LocalDateTime orderTime = LocalDateTimeUtil.of(order2.getCreateTime());
				
				return LocalDateTimeUtil.between(orderTime, LocalDateTimeUtil.now()).toDays() < 90;
			}else if(StrUtil.equals(payTime, "3")){
				// 代表今年以内
				// 先获取订单的时间
				LocalDateTime orderTime = LocalDateTimeUtil.of(order2.getCreateTime());
				int orderYear = orderTime.getYear();
				
				// 拿到现在的年份
				int nowYear = LocalDateTimeUtil.now().getYear();
				 
				return orderYear == nowYear;
			}else if(StrUtil.equals(payTime, "4")){
				// 代表今年以内
				// 先获取订单的时间
				LocalDateTime orderTime = LocalDateTimeUtil.of(order2.getCreateTime());
				int orderYear = orderTime.getYear();
				
				// 拿到现在的年份
				int nowYear = LocalDateTimeUtil.now().getYear();
				 
				return orderYear == nowYear-1;
			}else {
				StaticLog.error(new RuntimeException(("查询订单时，携带的提交订单的时间异常！")));
				return false;
			}
		}).collect(Collectors.toList());
	}
	
	/**
	 * 传入一个order，把order转换成ordervo
	 * @param orders order订单
	 * @return
	 */
	public List<OrderVo> ordersParseOrderVos(List<Order> orders){
		// 把order转换成OrderVO，为其设置List<OrderBook>属性
		return orders.stream().map(order->{
			// 通过当前订单的id查询对应的订单图书
			List<OrderBook> queryOrdersBookByOrderId = orderBookService.queryOrdersBookByOrderId(order.getId());
			
			// 遍历所有的订单图书，得到bookVO
			List<BookVo> collect = queryOrdersBookByOrderId.stream().map(orderBook->{
				Book bookById = bookService.getBookById(orderBook.getBookId());
				
				// 把每一个book转换成bookVo,返回出去
				return new BookVo(bookById);
			}).collect(Collectors.toList());
			
			// 再把每个订单转换成订单VO
			OrderVo orderVo = new OrderVo(order);
			orderVo.setBooks(collect);
			
			return orderVo;
		}).collect(Collectors.toList());
	}
}
